package com.dlu.safe_construction.controller;


import com.dlu.safe_construction.common.utils.QiniuCloudUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import com.dlu.safe_construction.common.ApiResult;
import com.dlu.safe_construction.common.LoginContext;
import com.dlu.safe_construction.common.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by  lijiaxing on 2022/4/3 20:52
 *
 * @author lijiaxing
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController implements BaseController {

    @PostMapping(path = "/upload.json", produces = APPLICATION_JSON)
    public ApiResult<String> uploadImg(@RequestParam MultipartFile image, HttpServletRequest request) {
        if (image.isEmpty()) {
            return ApiResult.fail(400);
        }

        try {
            byte[] bytes = image.getBytes();
            //文件名
            //String fileName = FileName.getFileName(image);
            String fileName = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            //上传工具类
            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            try {
                //使用base64方式上传到七牛云
                String key = qiniuUtil.put64image(bytes, fileName);
                return ApiResult.success(key);
            } catch (Exception e) {
                e.printStackTrace();
                return ApiResult.fail(500);
            }
        } catch (IOException e) {
            return ApiResult.fail(600);
        }
    }

    @GetMapping(path = "/download.json", produces = APPLICATION_JSON)
    public ApiResult<String> download(@RequestParam("objectKey") String objectKey, HttpServletResponse response) throws IOException {
        log.info(objectKey);
        String url = QiniuCloudUtil.download(objectKey);
        return ApiResult.success(url);
    }
}
